﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Applications.City.Entity;
using XingFuStudio.Pioneer.Entity;
using XingFuStudio.Pioneer.Net;
using XingFuStudio.Pioneer.Applications.City.Shop;
using FluorineFx.IO;
using XingFuStudio.Pioneer.Applications.City.Element;

namespace XingFuStudio.Pioneer.Applications.City.Operation {
    /// <summary>
    /// 公共操作
    /// </summary>
    public class OPCommon : OPBase{
        /// <summary>
        /// 调用方法的目标类
        /// </summary>
        //private readonly string Target = "CCityOilwell.callfunc";

        /// <summary>
        /// 创建业务对象
        /// </summary>
        /// <param name="httpManager"></param>
        /// <param name="account"></param>
        /// <param name="city"></param>
        /// <param name="config"></param>
        public OPCommon(HttpManager httpManager, AccountInfo account, CityInfo city){
            this.httpManager = httpManager;
            this.account = account;
            this.city = city;
        }

        /// <summary>
        /// 获取开心城市的登录ID
        /// </summary>
        /// <returns></returns>
        public string GetLoginId() {
            //获取AMF数据
            AMFMessage message = this.GetAMFMessage("CCityConfig.callfunc", "getInitConfig", 0);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data = (Dictionary<string, object>)content["data"];

            //返回登录ID
            return (string)data["loginid"];
        }

        /// <summary>
        /// 获取城市配置信息
        /// </summary>
        /// <param name="user"></param>
        public CityInfo GetCityInfo(UserInfo user) {
            //获取AMF数据
            AMFMessage message = this.GetAMFMessage("CCityConfig.callfunc", "getConfig", user.UserId);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data = (Dictionary<string, object>)content["data"];
            Dictionary<string, object> account = (Dictionary<string, object>)data["account"];

            //获取登录ID
            //this.loginId = (string)data["loginid"];

            //初始化城市信息对象
            CityInfo cityInfo = new CityInfo();
            //赋值城市信息
            cityInfo.CityName = (string)account["cash"];
            cityInfo.UserId = (string)account["uid"];
            cityInfo.UserName = (string)account["real_name"];
            cityInfo.Cash = Convert.ToInt32((string)account["cash"]);
            cityInfo.Energy = Convert.ToInt32((string)account["energy"]);
            cityInfo.Exp = Convert.ToInt32((string)account["xp"]);
            cityInfo.Gold = Convert.ToInt32((string)account["goldnum"]);
            cityInfo.Goods = Convert.ToInt32((string)account["goods"]);
            cityInfo.Level = Convert.ToInt32((string)account["level"]);
            cityInfo.Population = Convert.ToInt32((string)account["population"]);
            cityInfo.PopulationCap = Convert.ToInt32((string)account["populationcap"]);
            cityInfo.NextLevelExp = Convert.ToInt32((string)account["nextlevelxp"]);

            object tmpObject1 = null;
            data.TryGetValue("visiteget", out tmpObject1);
            if (tmpObject1 != null) {
                cityInfo.VisitGet = (Dictionary<string, object>)tmpObject1;
            }

            object tmpObject2 = null;
            data.TryGetValue("visithelp", out tmpObject2);
            if (tmpObject2 != null) {
                cityInfo.VisiteHelp = (Dictionary<string, object>)tmpObject2;
            }


            Dictionary<string, object> elementMessage = (Dictionary<string, object>)data["element"];
            List<object> elementObjects = ((object[])elementMessage["user"]).ToList();

            //初始化元素集合
            List<CityElement> elements = new List<CityElement>();

            foreach (object elementObject in elementObjects) {
                //转换成元素属性字典
                Dictionary<string, object> elementDictionary = (Dictionary<string, object>)elementObject;
                //调用工厂生成对应的元素对象
                CityElement element = ElementFactory.CreateElement((string)elementDictionary["classname"]);
                //初始化元素
                element.InitElement(elementDictionary);

                elements.Add(element);
            }

            //赋值城市元素列表属性
            cityInfo.Elements = elements;

            //获取升级元素数据
            Dictionary<string, object> uplevelData = (Dictionary<string, object>)data["userupleveldata"];
            //遍历升级元素
            foreach (string key in uplevelData.Keys) {
                UpLevelElementInfo info = new UpLevelElementInfo();

                Dictionary<string, object> item = (Dictionary<string, object>)uplevelData[key];

                info.InitiElementId = Convert.ToInt32(item["initeid"]);
                info.Level = Convert.ToInt32(item["curlevel"]);
                info.TargetOrderId = (string)item["targetid"];
                info.Total = Convert.ToInt32(item["total"]);
                info.UserId = (string)item["uid"];

                cityInfo.UpLevelElements.Add(info);
            }

            //获取升级配置
            Dictionary<string, object> uplevelConfig = (Dictionary<string, object>)data["uplevelsetting"];
            //遍历升级配置
            foreach (string key in uplevelConfig.Keys) {
                UpLevelConfigInfo info = new UpLevelConfigInfo();

                Dictionary<string, object> item = (Dictionary<string, object>)uplevelConfig[key];
                info.ElementId = Convert.ToInt32(item["eid"]);
                info.ElementName =(string)item["configname"];

                Dictionary<string, object> setting = (Dictionary<string, object>)item["setting"];

                foreach (string skey in setting.Keys) {
                    LevelConfigInfo level = new LevelConfigInfo();

                    Dictionary<string, object> lItem = (Dictionary<string, object>)setting[skey];
                    level.InitElementId = info.ElementId;
                    level.Level = Convert.ToInt32(lItem["level"]);
                    level.NewElementId = Convert.ToInt32(lItem["toeid"]);
                    level.Number = String.IsNullOrEmpty((string)lItem["num"]) ? 0 : Convert.ToInt32(lItem["num"]);

                    info.LevelConfigs.Add(level);
                }

                cityInfo.UpLevelConfigs.Add(info);
            }

            //获取AMF数据
            message = this.GetAMFMessage("CCityConfig.callfunc", "getConfigAfter", 0, 0);
            //解析数据
            content = (Dictionary<string, object>)message.Bodies[0].Content;
            data = (Dictionary<string, object>)content["data"];
            //account = (Dictionary<string, object>)data["account"];
            object dicValue = null;
            bool res = data.TryGetValue("factorystatus", out dicValue);
            if (res) {
                string status = (string)((Dictionary<string, object>)dicValue)["status"];
                switch (status) {
                    case "working":
                        cityInfo.FactoryStatus = ProductStatus.Working;
                        break;
                    case "complete":
                        cityInfo.FactoryStatus = ProductStatus.Complete;
                        break;
                    case "free":
                        cityInfo.FactoryStatus = ProductStatus.Waiting;
                        break;
                    default:
                        cityInfo.FactoryStatus = ProductStatus.None;
                        break;
                }
            } else {
                cityInfo.FactoryStatus = ProductStatus.None;
            }

            res = data.TryGetValue("useroilorder", out dicValue);
            if (res) {
                string status = (string)((Dictionary<string, object>)dicValue)["status"];
                switch (status) {
                    case "working":
                        cityInfo.OilwellStatus = ProductStatus.Working;
                        break;
                    case "complete":
                        cityInfo.OilwellStatus = ProductStatus.Complete;
                        break;
                    case "free":
                        cityInfo.OilwellStatus = ProductStatus.Waiting;
                        break;
                    default:
                        cityInfo.OilwellStatus = ProductStatus.None;
                        break;
                }
            } else {
                cityInfo.OilwellStatus = ProductStatus.None;
            }

            cityInfo.MyTrainStatus = ProductStatus.None;
            res = data.TryGetValue("trainOrders", out dicValue);
            if (res) {
                Object[] myTrains = (Object[])((Dictionary<string, object>)dicValue)["myTrains"];

                Object[] buyList = (Object[])((Dictionary<string, object>)dicValue)["buylist"];
                Object[] sellList = (Object[])((Dictionary<string, object>)dicValue)["selllist"];

                List<object> newList = new List<object>();
                newList.AddRange(buyList);
                newList.AddRange(sellList);

                cityInfo.MyTrainStatus = ProductStatus.Waiting;

                //遍历数据
                foreach (Dictionary<string, object> item in newList) {
                    string status = (string)item["status"];

                    if (status == "running") {
                        cityInfo.MyTrainStatus = ProductStatus.Working;
                        break;
                    }
                }

                if (myTrains.Length > 0) {
                    foreach (Dictionary<string, object> item in myTrains) {
                        TrainInfo train = new TrainInfo();

                        object trainProperty = null;

                        bool has = item.TryGetValue("fuid", out trainProperty);

                        if (has) {
                            train.Type = (string)item["type"] == "sell" ? TrainType.Sell : TrainType.Buy;
                            train.OName = (string)item["oname"];
                            train.OId = Convert.ToInt32((string)item["oid"]);
                            train.Goods = Convert.ToInt32((string)item["goods"]);
                            train.Cash = Convert.ToInt32((string)item["cash"]);
                            train.CityOrderId = (string)item["orderid"];

                            FriendInfo friend = new FriendInfo();
                            friend.UserId = (string)item["fuid"];
                            friend.UserName = (string)item["fname"];

                            train.TrainOwner = friend;
                        } else {
                            cityInfo.MyTrainStatus = ProductStatus.Complete;
                            train.Type = (string)item["type"] == "sell" ? TrainType.Sell : TrainType.Buy;
                            train.OName = (string)item["oname"];
                            train.OId = Convert.ToInt32((string)item["oid"]);
                            train.Goods = Convert.ToInt32((string)item["goods"]);
                            train.Cash = Convert.ToInt32((string)item["cash"]);
                        }

                        cityInfo.Trains.Add(train);
                    }
                }
            } else {
                cityInfo.MyTrainStatus = ProductStatus.None;
            }

            //返回城市信息
            return cityInfo;
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="shopType">商品类型</param>
        /// <returns></returns>
        public List<ShopItem> GetShopItems(ShopType shopType) {
            //获取AMF数据
            AMFMessage message = this.GetAMFMessage("CCityShop.callfunc", "getList", shopType.ToString().ToLower(), "", "");

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Object[] data = (Object[])content["data"];

            List<ShopItem> list = new List<ShopItem>();

            //遍历数据
            foreach (Dictionary<string, object> item in data) {
                //创建商品信息实例对象
                ShopItem shop = ShopFactory.CreateShop(shopType);
                //初始化商品信息
                shop.InitShop(item);
                //添加到列表
                list.Add(shop);
            }

            //返回商品列表
            return list;
        }
    }
}
